<template>
  <div class="group-detail">
    <!-- 头部背景图 -->
    <div class="group-header">
      <van-nav-bar
          :title="groupName"
          left-arrow
          :border="false"
          @click-left="router.back()"
          class="nav-bar"
      />
      <!-- 圈子信息 -->
      <div class="group-info">
        <van-image
            round
            width="80"
            height="80"
            :src="groupInfo.avatar"
            class="group-avatar"
        />
        <div class="group-text">
          <h2>{{ groupInfo.name }}</h2>
          <div class="stats">
            <span>动态数 {{ groupInfo.postCount }}</span>
            <span>圈友 {{ groupInfo.memberCount }}</span>
          </div>
        </div>
        <div class="group-follow" @click="toggleJoin">
          <van-icon
              :name="isJoined ? 'star' : 'star-o'"
              :color="isJoined ? '#ffd700' : '#fafafa'"
          />
          <spanb :style="{color:isJoined?'#ffd700' : '#fafafa',marginLeft:'10px'}">{{ isJoined ? '取关' : '关注' }}</spanb>
        </div>
      </div>
    </div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <!-- 动态列表 -->
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          class="list"
          @load="onLoad"
      >
        <div
            v-for="dynamic in dynamicList"
            :key="dynamic.id"
            class="dynamic-item"
            @click="showDynamicDetail(dynamic)"
        >
          <div class="header">
            <van-image
                round
                width="40"
                height="40"
                :src="dynamic.avatar"
            />
            <div class="user-info">
              <div class="username">{{ dynamic.nickname }}</div>
              <div class="time">{{ formatTime(dynamic.createTime) }} 第{{ dynamic.postCount }}贴</div>
            </div>
            <van-button
                v-if="!dynamic.isSelf"
                class="follow-button"
                size="mini"
                :type="dynamic.isFollowed ? 'default' : 'primary'"
                @click.stop="toggleFollow(dynamic)"
            >
              {{ dynamic.isFollowed ? '已关注' : '+ 关注' }}
            </van-button>
          </div>

          <div class="content">
            <div class="text" :class="{ 'collapsed': !dynamic.isExpanded }">
              {{ dynamic.content.slice(0, dynamic.isExpanded ? undefined : maxTextLength) }}
              <span v-if="dynamic.content.length > maxTextLength && !dynamic.isExpanded" @click.stop="toggleExpand(dynamic)">
                ...<span style="color: #ff4949">展开</span>
              </span>
              <span v-if="dynamic.content.length > maxTextLength && dynamic.isExpanded" @click.stop="toggleExpand(dynamic)">
                <span style="color: #ff4949">收起</span>
              </span>
            </div>
            <div class="media-list">
              <template v-for="(media, index) in dynamic.media" :key="index">
                <div v-if="isVideo(media.url)" class="video-wrapper" @click.stop="playVideo(media.url)">
                  <van-image
                      :width="getMediaWidth(dynamic.media.length)"
                      :height="getMediaWidth(dynamic.media.length)"
                      fit="cover"
                      :src="media.cover || '/video.png'"
                  />
                  <van-icon name="play-circle" class="play-icon" />
                </div>
                <van-image
                    v-else
                    :width="getMediaWidth(dynamic.media.length)"
                    :height="getMediaWidth(dynamic.media.length)"
                    :src="media.url"
                    @click.stop="previewMedia(media.url, dynamic.media.map(m => m.url))"
                />
              </template>
            </div>
          </div>

          <div class="footer">
            <van-tag plain type="primary"># {{dynamic.groupName}}</van-tag>
            <div class="actions">
              <div style="color: #666666">举报</div>
              <!-- 点赞 -->
              <div class="action-item" @click.stop="toggleLike(dynamic)">
                <van-icon
                    :name="dynamic.isLiked ? 'good-job' : 'good-job-o'"
                    :color="dynamic.isLiked ? '#ee0a24' : '#666'"
                />
                <span>{{ dynamic.likeCount }}</span>
              </div>

              <!-- 评论 -->
              <div class="action-item">
                <van-icon name="comment-o" />
                <span>{{ dynamic.commentCount }}</span>
              </div>

              <!-- 收藏 -->
              <div class="action-item" @click.stop="toggleFavorite(dynamic)">
                <van-icon
                    :name="dynamic.isFavorited ? 'star' : 'star-o'"
                    :color="dynamic.isFavorited ? '#ffd700' : '#666'"
                />
                <span>{{ dynamic.favoriteCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 弹窗：用于视频预览 -->
    <van-popup v-model:show="videoPreviewVisible" position="center" round>
      <video
          :src="currentVideoUrl"
          controls
          autoplay
          style="width: 100%; max-width: 600px; height: auto;"
      ></video>
    </van-popup>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {getDynamicList, followUser, likeDynamic, favoriteDynamic,getGroupDetail, followGroup} from '@/api/index.js';
import dayjs from 'dayjs';
import {useUserInfoStore} from "@/stores/userInfo.js";
import {useRouter,useRoute} from "vue-router";
import { showImagePreview } from 'vant';

const router = useRouter();
const route = useRoute();
const userInfoStore = useUserInfoStore();
const dynamicList = ref([]);
const loading = ref(false);
const finished = ref(false);
const pageParams = ref({current: 0, size: 5});
const total = ref(0);
const refreshing = ref(false); // 新增：下拉刷新状态
const maxTextLength = ref(20); // 设置最大显示字符数
const groupName= ref('');
const groupId = route.params.groupId;
// 新增视频封面缓存
const videoCovers = ref({});
// 当前播放的视频地址
const videoPreviewVisible = ref(false);
const currentVideoUrl = ref('');
// 圈子信息
const groupInfo = ref({});
const isJoined = ref(false);


onMounted(()=>{
  loadGroupDetail();
})

// 加载圈子详情
const loadGroupDetail = async () => {
  const res = await getGroupDetail(groupId);
  groupInfo.value = res;
  console.log(groupInfo.value)
  isJoined.value = res.isJoined;
  groupName.value=groupInfo.value.name+"圈";
};

// 判断是否为图片
const isImage = (url) => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url);
};

// 判断是否为视频
const isVideo = (url) => {
  return /\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(url);
};

// 获取视频封面方法
const getVideoCover = (url) => {
  return new Promise((resolve) => {
    if (videoCovers.value[url]) return resolve(videoCovers.value[url]);
    const video = document.createElement('video');
    video.crossOrigin = 'anonymous';
    video.muted = true;
    video.playsInline = true;
    video.src = url;
    video.addEventListener('loadeddata', () => {
      video.currentTime = 0.1;
    });
    video.addEventListener('seeked', () => {
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const dataUrl = canvas.toDataURL('image/jpeg');
      videoCovers.value[url] = dataUrl;
      resolve(dataUrl);
    });
    video.addEventListener('error', () => {
      resolve('/video.png');
    });
  });
};

// 图片预览
const previewMedia = (currentMedia, mediaList) => {
  if (isImage(currentMedia)) {
    showImagePreview({
      images: mediaList.filter(isImage),
      startPosition: mediaList.indexOf(currentMedia),
      closeable: true,
    });
  }
};

// 播放视频
const playVideo = (videoUrl) => {
  currentVideoUrl.value = videoUrl;
  videoPreviewVisible.value = true;
};

// 加载动态列表
const loadDynamics = async () => {
  try {
    const res = await getDynamicList({
      groupId: groupId,
      ...pageParams.value,
    });
    const processedList = res.list.map(dynamic => ({
      ...dynamic,
      isSelf: dynamic.nickname === userInfoStore.nickname,
      isExpanded: false,
      media: (dynamic.images || []).map(url => ({
        url,
        type: isVideo(url) ? 'video' : 'image',
        cover: null
      }))
    }));
    // 异步加载视频封面
    for (const dynamic of processedList) {
      for (const media of dynamic.media) {
        if (media.type === 'video') {
          media.cover = await getVideoCover(media.url);
        }
      }
    }
    dynamicList.value = [...dynamicList.value, ...processedList];
    total.value = res.total;
    finished.value = pageParams.value.current * pageParams.value.size >= total.value;
  } catch (error) {
    console.error('加载动态失败:', error);
    finished.value = true;
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 无限加载处理
const onLoad = () => {
  pageParams.value.current++;
  console.log("加载")
  loadDynamics();
};

// 下拉刷新处理
const onRefresh = () => {
  pageParams.value.current = 1;
  loadDynamics();
};

// 关注操作
const toggleFollow = async (dynamic) => {
  try {
    await followUser(dynamic.creator);
    dynamic.isFollowed = !dynamic.isFollowed;
  } catch (error) {
    console.error('关注操作失败:', error);
  }
};

// 加入/退出圈子
const toggleJoin = async () => {
  await followGroup(groupId);
  isJoined.value = !isJoined.value;
  groupInfo.value.memberCount += isJoined.value ? 1 : -1;
};

// 展开/收起操作
const toggleExpand = (dynamic) => {
  dynamic.isExpanded = !dynamic.isExpanded;
};

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

const toggleLike = async (dynamic) => {
  try {
    await likeDynamic(dynamic.id);
    dynamic.isLiked = !dynamic.isLiked;
    dynamic.likeCount += dynamic.isLiked ? 1 : -1;
  } catch (error) {
    console.error('操作失败:', error);
  }
};

const toggleFavorite = async (dynamic) => {
  try {
    await favoriteDynamic(dynamic.id);
    dynamic.isFavorited = !dynamic.isFavorited;
    dynamic.favoriteCount += dynamic.isFavorited ? 1 : -1;
  } catch (error) {
    console.error('操作失败:', error);
  }
};

const showDynamicDetail= (dynamic) => {
  router.push(`/dynamicDetail/${dynamic}`);
};

// 计算媒体项宽度
const getMediaWidth = (count) => {
  if (count < 3) {
    return `calc(100% / ${count} - 5px)`;
  }
  return '105px';
};
</script>

<style scoped>
.video-wrapper {
  position: relative;
  display: inline-block;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  color: rgba(255, 255, 255, 0.8);
  filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.5));
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 10px;
}
/* 头部背景图样式 */
.group-header {
  height: 180px;
  background-color: #666666;
  margin-top: 46px;
}

/* 圈子信息面板 */
.group-info {
  display: flex;
}

.group-avatar{
  margin: auto;
}

.stats {
  color: white;
  margin-bottom: 16px;

  span {
    margin-right: 20px;
  }
}

.group-follow{
  margin:auto;
  font-size: 20px;
}

.dynamic-item {
  margin: 10px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 15px;
}

.user-info {
  flex: 1;
}

.username {
  font-weight: 500;
  font-size: 14px;
}

.time {
  font-size: 12px;
  color: #666;
}

.footer {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  margin-top: 10px;
  display: flex;
  gap: 20px;
  align-items: center;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 20px;
  color: #666;

  &:active {
    opacity: 0.6;
  }
}
.list{
  padding-bottom: 50px;
}

.nav-bar{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

</style>
